﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPF_ObservableCollection_List
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    /// <summary>
    /// Interaction logic for TestWindow.xaml
    /// </summary>
    public partial class TestWindow : Window
    {
        TestWindowViewMode viewMode = new TestWindowViewMode();
        public TestWindow()
        {
            InitializeComponent();
            this.DataContext = viewMode;
        }

        private void btnObservable_Click(object sender, RoutedEventArgs e)
        {
            viewMode.Refresh1();
        }

        private void btnList_Click(object sender, RoutedEventArgs e)
        {
            viewMode.Refresh2();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //string path = @"F:\Test10000\";
            //for (int i = 1; i <= 10000; i++)
            //{
            //    File.Create(path + System.IO.Path.GetRandomFileName());
            //}

            //string path = @"F:\Test10000\";
            //for (int i = 1; i <= 100; i++)
            //{
            //  Directory.CreateDirectory(path + System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName()));
            //  //.Create(path + System.IO.Path.GetRandomFileName());
            //}

        }
    }


    internal class TestWindowViewMode : DispatcherObject, INotifyPropertyChanged
    {
        string testPath = @"f:\Test10000\";
        bool isStopTag;
        int pageSize = 200;

        FileItem GetFileItem(string filePath)
        {
            FileItem item = new FileItem() { FullPath = filePath };
            return item;
        }

        #region data source 11
        /// <summary>
        /// files and directories in current directory, display in listview
        /// </summary>
        RangeObservableCollection<FileItem> allFiles1 = new RangeObservableCollection<FileItem>();
        /// <summary>
        ///  files and directories in current directory, display in listview
        /// </summary>
        public RangeObservableCollection<FileItem> AllFiles1
        {
            get { return allFiles1; }
            set
            {
                if (allFiles1 != value)
                    allFiles1 = value;
                NotifyPropertyChanged("AllFiles1");
            }
        }
        #endregion

        #region datasource 22

        /// <summary>
        /// files and directories in current directory, display in listview
        /// </summary>
        List<FileItem> allFiles2 = new List<FileItem>();
        /// <summary>
        ///  files and directories in current directory, display in listview
        /// </summary>
        public List<FileItem> AllFiles2
        {
            get { return allFiles2; }
            set
            {
                if (allFiles2 != value)
                    allFiles2 = value;
                NotifyPropertyChanged("AllFiles2");
            }
        }
        #endregion

        #region load data method---1
        Thread thread1;
        /// <summary>
        /// when current directory path change ,refresh listview
        /// </summary>
        public void Refresh1()
        {
            isStopTag = true;
            CommonProvider.Log("load files for view start==");
            IEnumerable<string> files = null;
            try
            {
                files = Directory.EnumerateFileSystemEntries(testPath)
                 .Where(o => CommonProvider.IsDisplay(o));
            }
            catch (Exception ex)
            {
                CommonProvider.Log(ex);
            }
            if (files == null) return;
            CommonProvider.Log("load files for view Enumerate ok ");

            allFiles1.Clear();
            allFiles1.AddRange(files.Select(o => GetFileItem(o)).Take(pageSize));
            CommonProvider.Log("load files for view first page  files  ok ");

            if (allFiles1.Count() < pageSize) return;
            RunLastTask1();
        }

        /// <summary>
        /// continue load last files, start thead
        /// </summary>
        void RunLastTask1()
        {
            isStopTag = false;
            thread1 = new Thread(new ThreadStart(LoadLastFiles));
            thread1.Name = "LoadingForView";
            thread1.IsBackground = true;
            thread1.Start();
        }

        /// <summary>
        /// loading last file task 
        /// </summary>
        void LoadLastFiles()
        {
            int pageIndex = 1;
            var files = Directory.EnumerateFileSystemEntries(testPath);
            DateTime lastTime = DateTime.Now;
            int pageRealCount = pageSize;


            DateTime dtBegin = DateTime.Now;
            CommonProvider.Log("====loading begin:" + (DateTime.Now - dtBegin).TotalSeconds);

            #region rangeObservableCollection
            isStopTag = true;
            while (isStopTag)
            {
                var pageFiles = files.Select(o => GetFileItem(o)).Skip(pageSize * pageIndex).Take(pageSize).ToList();
                Invoke(delegate
                {
                    allFiles1.AddRange(pageFiles);
                });
                pageRealCount = pageFiles.Count();
                if (pageRealCount < pageSize)
                    isStopTag = false;
                pageIndex++;
                CommonProvider.Log(" ====Refresh Data ");
            }
            #endregion
            CommonProvider.Log("====loading ok:" + (DateTime.Now - dtBegin).TotalSeconds);
            CommonProvider.Log("====current ItemsCount:" + allFiles1.Count.ToString());
        }
        #endregion

        #region load data method---2
        Thread thread2;
        /// <summary>
        /// when current directory path change ,refresh listview
        /// </summary>
        public void Refresh2()
        {
            isStopTag = true;
            CommonProvider.Log("22=load files for view start==");
            IEnumerable<string> files = null;
            try
            {
                files = Directory.EnumerateFileSystemEntries(testPath)
                 .Where(o => CommonProvider.IsDisplay(o));
            }
            catch (Exception ex)
            {
                CommonProvider.Log(ex);
            }
            if (files == null) return;
            CommonProvider.Log("22==load files for view Enumerate ok ");

            allFiles2.Clear();

            allFiles2 = files.Select(o => GetFileItem(o)).Take(pageSize).ToList();
            NotifyPropertyChanged("AllFiles2");
            CommonProvider.Log("22==load files for view first page  files  ok ");

            if (allFiles2.Count() < pageSize) return;
            RunLastTask2();
        }

        /// <summary>
        /// continue load last files, start thead
        /// </summary>
        void RunLastTask2()
        {
            isStopTag = false;
            thread2 = new Thread(new ThreadStart(LoadLastFiles2));
            thread2.Name = "LoadingForView222";
            thread2.IsBackground = true;
            thread2.Start();
        }

        /// <summary>
        /// loading last file task 
        /// </summary>
        void LoadLastFiles2()
        {
            var files = Directory.EnumerateFileSystemEntries(testPath);
            DateTime lastTime = DateTime.Now;
            int pageRealCount = pageSize;


            DateTime dtBegin = DateTime.Now;
            CommonProvider.Log("22====loading begin:" + (DateTime.Now - dtBegin).TotalSeconds);

            int refreshInterval = 1;
            foreach (string file in files.Skip(pageSize))
            {
                AllFiles2.Add(GetFileItem(file));

                if ((DateTime.Now - lastTime).TotalSeconds >= refreshInterval)
                {
                    lastTime = DateTime.Now;
                    CommonProvider.Log("22 ====Refresh Data ");
                    NotifyPropertyChanged("AllFiles2");
                }
            }
            CommonProvider.Log("22====loading ok:" + (DateTime.Now - dtBegin).TotalSeconds);
            CommonProvider.Log("22====current ItemsCount:" + allFiles2.Count.ToString());
        }
        #endregion

        void Invoke(Action a)
        {
            this.Dispatcher.Invoke(a);
        }

        void Log(object logObj = null)
        {
            string str = (logObj == null ? "Null" : logObj.ToString());
            string logFormat = "{0} | {1}";
            Debug.WriteLine(string.Format(logFormat, DateTime.Now.ToString("hh:mm:ss fff"), str));
        }

        #region property changed
        public void NotifyPropertyChanged(string name)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        #endregion

    }
}
